const { createApp, reactive, toRefs, computed, nextTick } = Vue;
const app = createApp({
	setup() {
		const todos = reactive({
			todoList: [
				{ id: '001', text: '写300行代码', isCompleted: false, isEditing: false },
				{ id: '002', text: '读50页书', isCompleted: true, isEditing: false }
			],
			status: 'All',
			beforeText: ''

		})

		// 添加新的待办事项
		const handleNewTodo = (e) => {
			const text = e.target.value.trim();
			if (!text) {
				alert('请输入待办事项')
				return
			}
			todos.todoList.push({
				id: Date.now().toString(),
				text,
				isCompleted: false
			})

			e.target.value = '';
		}

		// 剩余待办事项数量
		const remaining = computed(() => {
			return todos.todoList.filter(item => !item.isCompleted).length
		})

		// 清除已完成事项
		const handleClearCompleted = () => {
			todos.todoList = todos.todoList.filter(item => !item.isCompleted)
		}

		// 根据状态过滤事项
		const hanldeFilterTodoStatus = (status) => {
			todos.status = status
		}

		// 通过计算属性 得到的列表
		const list = computed(() => {
			if (todos.status === 'All') {
				return todos.todoList
			} else if (todos.status === 'active') {
				return todos.todoList.filter(item => !item.isCompleted)
			} else {
				return todos.todoList.filter(item => item.isCompleted)
			}

		})

		// 全选/取消全选
		const handleToggleAll = (e) => {
			// console.log(e.target.checked);
			todos.todoList.forEach(item => {
				item.isCompleted = e.target.checked
			})

		}
		// 删除单个待办事项
		const handelRemoveTodo = (id) => {
			todos.todoList = todos.todoList.filter(item => item.id !== id)
		}

		// 双击事件
		const handleDoubleClickTodo = (item, e) => {
			if (item.isCompleted) {
				alert('该事项已完成，无法编辑');
				return
			}
			// 保存编辑之前的文本内容
			todos.beforeText = item.text
			// console.log(item);
			item.isEditing = true
			// 让输入框获取焦点
			console.log(e.target.parentNode.nextSibling);

			nextTick(() => {
				e.target.parentNode.nextSibling.focus()
			})
		}

		// 处理编辑
		const handleEditTodo = (item) => {
			// 取消正在编辑
			item.isEditing = false
		}

		// 取消编辑
		const handleCancelEditTodo = (item) => {
			// 取消正在编辑 TODO
			// 1. 取消编辑状态
			item.isEditing = false
			// 2. 还原文本
			item.text = todos.beforeText
			// 3. 清空备份文本
			todos.beforeText = ''

		}

		return {
			...toRefs(todos),
			handleNewTodo,
			remaining,
			handleClearCompleted,
			hanldeFilterTodoStatus,
			list,
			handleToggleAll,
			handelRemoveTodo,
			handleDoubleClickTodo,
			handleEditTodo,
			handleCancelEditTodo
		}
	}
})

app.mount("#app")
